﻿<%@ WebHandler Language="C#" Class="RbContainerStepPlanMaint" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using ReportBusiness;

/**
 * Description: 热表转工排产维护
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date: 2022.12.1
 **/

public class RbContainerStepPlanMaint : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getUserInfo":
                        r = getUserInfo(jObject);//查询用户信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "saveSingleRowData":
                        r = saveSingleRowData(jObject);//保存单行数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "changeShipLocked":
                        r = changeShipLocked(jObject);//切换锁定状态
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "multipleSave":
                        r = multipleSave(jObject);//批量保存
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT csp.containerstepplanid,f.factoryname,cci.productname,cci.productdescription,cci.containername,csp.workflowstepname,csp.plannedstartdate,
       DECODE(csp.isshiplocked,1,'已锁定','未锁定') isshiplocked,
       DECODE(csp.plannedfinishdate,NULL,'未维护','已维护') status,
       e.fullname jijiaplaner,csp.stepplancreatedate,e2.fullname rbplaner,csp.stepplanshipdate,csp.plannedfinishdate,
       f2.factoryname specfactoryname,cci.qty,CASE WHEN t.qty IS NOT NULL THEN '已开卡' ELSE '未开卡' END isstart
FROM containerstepplan csp
LEFT JOIN containercurrentinfo cci ON csp.containerid = cci.containerid
LEFT JOIN employee e ON e.employeeid = csp.stepplancreateemployeeid
LEFT JOIN employee e2 ON e2.employeeid = csp.stepplanshipemployeeid
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
LEFT JOIN factory f2 ON f2.factoryid = csp.specfactoryid
LEFT JOIN 
(
   SELECT cub.containerid,cub.workflowstepname,COUNT(cub.subcontainerid) qty
   FROM containersubcontainer cub
   GROUP BY cub.containerid,cub.workflowstepname
) t ON t.containerid = cci.containerid AND t.workflowstepname = csp.workflowstepname
WHERE csp.plantype = 2";
        //主制分厂
        if (jObject["factoryname"] != null && jObject["factoryname"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryname = '{0}'", jObject["factoryname"].ToString());
        }

        //承制分厂
        if (jObject["specfactoryname"] != null && jObject["specfactoryname"].ToString() != "")
        {
            sql += string.Format(" AND f2.factoryname = '{0}'", jObject["specfactoryname"].ToString());
        }

        //零件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //批次号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }
        
        //计划发出时间
        if (jObject["plannedstartdate"] != null && jObject["plannedstartdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["plannedstartdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(csp.plannedstartdate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(csp.plannedstartdate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        //计划完成时间
        if (jObject["plannedfinishdate"] != null && jObject["plannedfinishdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["plannedfinishdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(csp.plannedfinishdate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(csp.plannedfinishdate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        //维护状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            string status = jObject["status"].ToString();
            if (status == "已维护")
            {
                sql += " AND csp.plannedfinishdate IS NOT NULL";
            }
            else
            {
                sql += " AND csp.plannedfinishdate IS NULL";
            }
        }

        //锁定状态
        if (jObject["lockstatus"] != null && jObject["lockstatus"].ToString() != "")
        {
            string lockstatus = jObject["lockstatus"].ToString();
            if (lockstatus == "已锁定")
            {
                sql += " AND csp.isshiplocked = 1";
            }
            else
            {
                sql += " AND NVL(csp.isshiplocked,0) = 0";
            }
        }

        //热表是否开卡
        if (jObject["isstart"] != null && jObject["isstart"].ToString() != "")
        {
            string isstart = jObject["isstart"].ToString();
            if (isstart == "已开卡")
            {
                sql += " AND t.qty IS NOT NULL ";
            }
            else
            {
                sql += " AND t.qty IS NULL ";
            }
        }
        
        return sql;
    }

    //查询用户信息
    Result getUserInfo(JObject jObject)
    {
        string sql = @"
SELECT e.employeeid,e.fullname,f.factoryid,f.factoryname,
       listagg(rd.rolename,'、') WITHIN GROUP (ORDER BY rd.rolename) rolename
FROM employee e
LEFT JOIN Sessionvalues sv ON sv.employeeid = e.employeeid
LEFT JOIN factory f ON f.factoryid = sv.factoryid
LEFT JOIN employeerole er ON er.employeeid = e.employeeid
LEFT JOIN Roledef rd ON rd.roleid = er.roleid
WHERE e.employeeid = '{0}'
GROUP BY e.employeeid,e.fullname,f.factoryid,f.factoryname";
        sql = string.Format(sql,jObject["uid"].ToString());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //保存一条记录
    Result saveSingleRowData(JObject jObject)
    {
        string sql = @"
UPDATE containerstepplan csp SET csp.plannedfinishdate = to_date('{0}','yyyy/mm/dd'),
                                 csp.stepplanshipdate = SYSDATE,
                                 csp.stepplanshipemployeeid = '{1}',
                                 csp.isshiplocked = 1
WHERE csp.containerstepplanid = '{2}'";
        string plannedfinishdate = jObject["plannedfinishdate"].ToString();
        if (plannedfinishdate.IndexOf(' ') > -1)
        {
            plannedfinishdate = plannedfinishdate.Split(' ')[0];
        }
        sql = string.Format(sql, plannedfinishdate, jObject["uid"].ToString(), jObject["containerstepplanid"].ToString());
        int updatedRowCount = dal.ExecuteSql(sql);
        Result r = new Result();
        r.data = null;
        r.total = Convert.ToInt32(updatedRowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
    
    //切换锁定状态
    Result changeShipLocked(JObject jObject)
    {
        string sql = @"UPDATE containerstepplan csp SET csp.isshiplocked = {0} WHERE csp.containerstepplanid = '{1}'";
        sql = string.Format(sql, jObject["isshiplocked"].ToString(), jObject["containerstepplanid"].ToString());
        int updatedRowCount = dal.ExecuteSql(sql);
        Result r = new Result();
        r.data = null;
        r.total = Convert.ToInt32(updatedRowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //批量保存
    Result multipleSave(JObject jObject)
    {
        JArray arr = JArray.Parse(jObject["multipleSaveData"].ToString());
        string uid = jObject["uid"].ToString();
        ArrayList sqlList = new ArrayList();
        string sql = "";
        foreach (var item in arr)
        {
            sql = @"
UPDATE containerstepplan csp SET csp.plannedfinishdate = to_date('{0}','yyyy/mm/dd'),
                                 csp.stepplanshipdate = SYSDATE,
                                 csp.stepplanshipemployeeid = '{1}',
                                 csp.isshiplocked = 1
WHERE csp.containerstepplanid = '{2}'
";
            string plannedfinishdate = item["plannedfinishdate"].ToString();
            if (plannedfinishdate.IndexOf(' ') > -1)
            {
                plannedfinishdate = plannedfinishdate.Split(' ')[0];
            }
            sql = string.Format(sql, plannedfinishdate, uid, item["containerstepplanid"].ToString());
            sqlList.Add(sql);
        }

        dal.ExecuteSqlTran(sqlList);
        Result r = new Result();
        r.data = null;
        r.total = Convert.ToInt32(arr.Count);
        r.meta = new Result.Meta(200, "添加成功");
        return r;
    }
}